<template>
    <div class="main">
        <div class="filter-container">
            <el-button type="primary" icon="el-icon-plus" class="filter-item" @click="chooseGoods">添加商品</el-button>
            <el-button type="primary" icon="el-icon-plus" class="filter-item" @click="chooseGoodsPackage" plain>添加套餐</el-button>
            <el-button v-if="form.crushGoodsList.length>8"  type="success" class="filter-item fr" @click="save">保 存</el-button>
        </div>
        <el-form :model="form" size="medium" ref="form" label-width="0px">
            <el-table :data="form.crushGoodsList" v-loading="listLoading" element-loading-text="给我一点时间">
                <el-table-column align="center" type="expand" width="100">
                    <template slot-scope="scope" v-if="scope.row.type===1 && scope.row.goodsAttr.filter(item=>item.deleteFlag!==0).length">
                        <el-table :data="scope.row.goodsAttr.filter(item=>item.deleteFlag!==0)" highlight-current-row border>
                            <el-table-column align="center" label="图库" width="100" fixed>
                                <template slot-scope="$scope">
                                    <div class="avatar-uploader">
                                        <label class="el-upload el-upload-text" style="width: 80px; height: 80px; line-height: 82px">
                                            <img v-if="$scope.row.skuImage" :src="$scope.row.skuImage" alt="">
                                            <i v-if="!$scope.row.skuImage" class="el-icon-plus avatar-uploader-icon"></i>
                                            <input type="file" class="el-upload__input" accept="image/*" @change="uploadAttrImg($scope.row, $event)">
                                        </label>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column v-for="(item, index) in [{id: 'attrId1',prop: 'attrValue1'},{id:'attrId2',prop: 'attrValue2'},{id:'attrId3',prop: 'attrValue3'},{id:'attrId4',prop: 'attrValue4'},{id:'attrId5',prop: 'attrValue5'},{id:'attrId6',prop: 'attrValue6'}]" v-if="scope.row.goodsAttr[0][item.id]" :key="index" align="center" :label="'属性值'+(index+1)" :prop="item.prop" min-width="100px">
                            </el-table-column>
                            <!--<el-table-column align="center" label="财务价" min-width="70px">
                                <template slot-scope="$scope">
                                    <el-form-item :prop="'crushGoodsList.'+scope.$index+'.goodsAttr['+$scope.$index+'].financePrice'" :rules="commonRules.priceRuleNull" style="margin: 30px 0">
                                        <el-input type="number" v-model="$scope.row.financePrice" style="width: 100%"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="成本价" min-width="70px">
                                <template slot-scope="$scope">
                                    <el-form-item :prop="'crushGoodsList.'+scope.$index+'.goodsAttr['+$scope.$index+'].costPrice'" :rules="commonRules.priceRuleNull" style="margin: 30px 0">
                                        <el-input type="number" v-model="$scope.row.costPrice" style="width: 100%"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>-->
                            <el-table-column align="center" label="市场价" min-width="70px">
                                <template slot-scope="$scope">
                                    <el-form-item :prop="'crushGoodsList.'+scope.$index+'.goodsAttr['+$scope.$index+'].marketValue'" :rules="commonRules.priceRule" style="margin: 30px 0">
                                        <el-input type="number" v-model="$scope.row.marketValue" style="width: 100%"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="销售价" min-width="70px">
                                <template slot-scope="$scope">
                                    <el-form-item :prop="'crushGoodsList.'+scope.$index+'.goodsAttr['+$scope.$index+'].price'" :rules="commonRules.priceRule" style="margin: 30px 0">
                                        <el-input type="number" v-model="$scope.row.price" style="width: 100%" @change="calcOtherPrice(scope.$index, $scope.$index)"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="VIP价" min-width="70px">
                                <template slot-scope="$scope">
                                    <el-form-item :prop="'crushGoodsList.'+scope.$index+'.goodsAttr['+$scope.$index+'].regionPrice'" :rules="commonRules.priceRule" style="margin: 30px 0">
                                        <el-input type="number"  v-model="$scope.row.maximumCommission == 0?$scope.row.price:$scope.row.regionPrice" style="width: 100%" placeholder="自动生成" disabled></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="钻石价" min-width="70px">
                                <template slot-scope="$scope">
                                    <el-form-item :prop="'crushGoodsList.'+scope.$index+'.goodsAttr['+$scope.$index+'].diamondPrice'" :rules="commonRules.priceRule" style="margin: 30px 0">
                                        <el-input type="number"  v-model="$scope.row.maximumCommission == 0?$scope.row.price:$scope.row.diamondPrice||0" style="width: 100%" placeholder="自动生成" disabled></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="董事价" min-width="70px">
                                <template slot-scope="$scope">
                                    <el-form-item :prop="'crushGoodsList.'+scope.$index+'.goodsAttr['+$scope.$index+'].directorPrice'" :rules="commonRules.priceRule" style="margin: 30px 0">
                                        <el-input type="number"  v-model="$scope.row.maximumCommission == 0?$scope.row.price:$scope.row.directorPrice" style="width: 100%" placeholder="自动生成" disabled></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <!--<el-table-column align="center" label="佣金类型">
                                <template slot-scope="$scope">
                                    <el-select v-model="$scope.row.commissionType" style="width: 100%">
                                        <el-option :key="1" label="数值(元)" :value="1"></el-option>
                                        <el-option :key="2" label="比例(%)" :value="2"></el-option>
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="佣金数值" min-width="70px">
                                <template slot-scope="$scope">
                                    <el-form-item :prop="'crushGoodsList.'+scope.$index+'.goodsAttr['+$scope.$index+'].commission'" :rules="$scope.row.commissionType===1?commonRules.priceRule : commonRules.percentRule" style="margin: 30px 0">
                                        <el-input type="number" v-model="$scope.row.commission" style="width: 100%"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>-->
                            <el-table-column align="center" label="最高佣金" min-width="70px">
                                <template slot-scope="$scope">
                                    <el-form-item :prop="'crushGoodsList.'+scope.$index+'.goodsAttr['+$scope.$index+'].maximumCommission'" :rules="commonRules.priceRuleZero" style="margin: 30px 0">
                                        <el-input type="number" placeholder="小于兰蜜价" v-model="$scope.row.maximumCommission" style="width: 100%" @change="calcOtherPrice(scope.$index, $scope.$index)"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="库存数" prop="totalSkuNumber" min-width="86px">
                                <template slot-scope="$scope">
                                    {{$scope.row.totalSkuNumber}}
                                    <div v-if="!$scope.row.totalSkuNumber" style="color: red">库存不足</div>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="已售" prop="soldNumber" min-width="86px"></el-table-column>
                            <!--<el-table-column align="center" label="库存数" min-width="86px">
                                <template slot-scope="$scope">
                                    可分配：{{$scope.row.totalSkuNumber}}<br/>
                                    已售：{{($scope.row.soldNumber||0)}}<br/>
                                    可卖：{{($scope.row.distributedSkuNumber||0)}}<br/>
                                    <el-form-item v-if="$scope.row.totalSkuNumber+($scope.row.distributedSkuNumber||0)" :prop="'crushGoodsList.'+scope.$index+'.goodsAttr['+$scope.$index+'].skuNumber'" :rules="commonRules.skuNumberRule" style="margin-bottom: 30px">
                                        <el-input-number v-model="$scope.row.skuNumber" :min="0" :max="$scope.row.totalSkuNumber+($scope.row.distributedSkuNumber||0)" :precision="0" :controls="false" style="width: 100%"></el-input-number>
                                    </el-form-item>
                                    <span v-else style="color: red">库存不足</span>
                                </template>
                            </el-table-column>-->
                            <!--<el-table-column align="center" label="数量" min-width="70px">
                                <template slot-scope="$scope">
                                    <el-form-item :prop="'crushGoodsList.'+scope.$index+'.goodsAttr['+$scope.$index+'].number'" :rules="commonRules.numberRule" style="margin: 30px 0">
                                        <el-input type="number" v-model="$scope.row.number" style="width: 100%"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>-->
                            <el-table-column align="center" label="是否上架" width="80">
                                <template slot-scope="$scope">
                                    <el-switch
                                            v-model="$scope.row.upshelf"
                                            active-color="#13ce66"
                                            inactive-color="#ff4949"
                                            :active-value="1"
                                            :inactive-value="0">
                                    </el-switch>
                                </template>
                            </el-table-column>
                            <!--<el-table-column align="center" label="操作" width="60" fixed="right" v-if="scope.row.goodsAttr.filter(item=>item.deleteFlag!==0).length>1">
                                <template slot-scope="$scope">
                                    <a href="javascript: void(0);" class="el-icon-remove" @click="delAttr(scope.$index, $scope.$index)"></a>
                                </template>
                            </el-table-column>-->
                        </el-table>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="类型" width="120">
                    <template slot-scope="scope">
                        <span v-text="itemTypes[scope.row.type-1]"></span>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="名称">
                    <template slot-scope="scope">
                        <a style="color: #409eff" target="_blank" :href="getUrl({id: scope.row.goodsId || scope.row.packageId, fromType: 2, goodsType: scope.row.type, activityId: scope.row.crushId, packType: ''})">
                            {{scope.row.type ===1 ? scope.row.goodsName: scope.row.packageName}}
                        </a>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="分享基数" width="200">
                  <template slot-scope="scope">
                    <el-form-item :prop="'crushGoodsList['+scope.$index+'].shareCardinality'" :rules="commonRules.skuNumberRule" style="margin-top: 22px">
                      <el-input v-model="scope.row.shareCardinality" style="width: 100%;"></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="用户限购数量【0代表不限购】" width="220">
                    <template slot-scope="scope">
                        <el-form-item :prop="'crushGoodsList['+scope.$index+'].userQuantity'" :rules="commonRules.skuNumberRule" style="margin-top: 22px">
                            <el-input v-model="scope.row.userQuantity" style="width: 100%;"></el-input>
                        </el-form-item>
                    </template>
                </el-table-column>
                <!--<el-table-column align="center" label="是否启用">
                    <template slot-scope="scope">
                        <el-switch
                                v-model="scope.row.status"
                                active-color="#13ce66"
                                inactive-color="#ff4949"
                                :active-value="1"
                                :inactive-value="2">
                        </el-switch>
                    </template>
                </el-table-column>-->
                <el-table-column align="center" label="排序" width="120">
                    <template slot-scope="scope">
                        <el-input type="number" v-model.number="scope.row.sort"></el-input>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="操作" width="120" fixed="right">
                    <template slot-scope="scope">
                        <a href="javascript: void(0);" class="el-icon-remove" @click="delItem(scope.row, scope.$index)"></a>
                    </template>
                </el-table-column>
            </el-table>
            <div style="text-align: center; padding: 20px">
                <el-button type="success" @click="save" :loading="btnLoading">保 存</el-button>
            </div>
        </el-form>
    </div>
</template>
<script>
  import differenceBy from 'lodash/differenceBy';
  export default {
    name: 'activitySecKillGoodsList',
    props: {
      id: { default: '' }
    },
    data() {
      return {
        startTime: this.$route.query.start,
        itemTypes: ['商品', '套餐'],

        listLoading: false,
        listQuery: {
          id: this.id,
          userId: this.$store.getters.userId
        },
        form: {
          crushGoodsList: [],
          goodsAttr: [],
        },
        btnLoading: false
      }
    },
    created(){
      this.getList();
    },
    methods: {
      getList(){
        this.listLoading = true;
        this.request({
          url: '/bsnl-product/crushgoods/details',
          method: 'get',
          params: this.listQuery
        }).then(({data}) => {
          if(data){
            this.form = data;
            this.form.crushGoodsList.filter(i => i.type===1).map(item => {
              item.goodsAttr = this.form.goodsAttr.filter(subItem => item.goodsId === subItem.goodsId );
              console.log(item.goodsAttr)
            })
          }
          this.listLoading = false;
        }).catch(err => {
          console.log(err);
          this.listLoading = false;
        });
      },
      // 选择商品
      chooseGoods(){
        let goods= this.form.crushGoodsList.filter(item => item.type === 1).map(i => {
          return {
            goodsId: i.goodsId,
            name: i.goodsName
          }
        });

        this.goodsChoose({}, goods).then(val => {
          let goodsList = this.form.crushGoodsList.filter(item => item.type ===1);
          let needDelGoods = differenceBy(goodsList, val, 'goodsId');
          let needAddGoods = differenceBy(val, goodsList, 'goodsId');
          let ids = [];
          needDelGoods.map(item => {
            if(item.id){
              ids.push(item);
            }
          });

          if(ids.length){
            this.request({
              url: '/bsnl-product/crushgoods/status',
              method: 'post',
              data: {ids}
            }).then(() => {
              this.form.crushGoodsList = (differenceBy(this.form.crushGoodsList, needDelGoods, 'goodsId'));
            }).catch(err => {
              console.log(err);
            });
          } else {
            this.form.crushGoodsList = (differenceBy(this.form.crushGoodsList, needDelGoods, 'goodsId'));
          }

          let timeGoods = [];
          needAddGoods.map((item) => {
            if (item.isSell ===0 && item.sellTime && new Date(item.sellTime).getTime() > new Date(this.startTime).getTime()){
              timeGoods.push((timeGoods.length+1)+'、'+item.name+`【开售时间：${item.sellTime}】`)
            }
            else {
              this.request({
                url: '/bsnl-product/goods/details',
                method: 'get',
                params: { id: item.id }
              }).then(({data}) => {
                let { goodsAttr } = data;
                // goodsAttr.map(item=> item.skuNumber=item.totalSkuNumber);
                goodsAttr.map(item => item.soldNumber=0);
                this.form.crushGoodsList.push({
                  goodsId: item.goodsId,
                  goodsName: item.name,
                  type: 1,
                  status: 1,
                  crushId: this.id,
                  id: null,
                  userQuantity: 0,
                  shareCardinality: 0,
                  goodsAttr
                });
              });
            }
          });
          if(timeGoods.length){
            this.$alert(`以下商品添加失败<span style="color: red">【商品开售时间晚于活动开始时间】</span>：<br/><br/><div class="time-goods-list">${timeGoods.join('<br/>')}</div>`, '提示', {
              confirmButtonText: '确定',
              dangerouslyUseHTMLString: true
            });
          }
        }).catch(err => {
          this.form.crushGoodsList = this.form.crushGoodsList.filter(item => item.type !==1);
        });
      },
      // 选择套餐
      chooseGoodsPackage(){
        let selected = this.form.crushGoodsList.filter(item=>item.type===2).map(item => {
          return {
            packageId: item.packageId,
            name: item.packageName
          }
        });
        this.packageChoose({}, selected).then(val => {
          let packageList = this.form.crushGoodsList.filter(item => item.type ===2);
          let needDelPackage = differenceBy(packageList, val, 'packageId');
          let needAddPackage = differenceBy(val, packageList, 'packageId');

          let ids = [];
          needDelPackage.map(item => {
            if(item.id){
              ids.push({id: item.id});
            }
          });

          if(ids.length){
            this.request({
              url: '/bsnl-product/crushgoods/status',
              method: 'post',
              data: {ids}
            }).then(() => {
              this.form.crushGoodsList = (differenceBy(this.form.crushGoodsList, needDelPackage, 'packageId'));
            }).catch(err => {
              console.log(err);
            });
          }
          else{
            this.form.crushGoodsList = (differenceBy(this.form.crushGoodsList, needDelPackage, 'packageId'));
          }

          needAddPackage.map((item) => {
            this.form.crushGoodsList.push({
              crushId: this.id,
              type: 2,
              status: 1,
              userQuantity: 0,
              shareCardinality: 0,
              packageId: item.packageId,
              packageName: item.name
            });
          });
        });
      },
      delItem(row, index){
        this.$confirm(row.id?`该删除将直接从数据库删除，确定要删除吗?`:`确定要删除吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if(row.id){
            this.request({
              url: '/bsnl-product/crushgoods/status',
              method: 'post',
              data: {
                ids: [{id: row.id}],
              }
            }).then(() => {
              this.form.crushGoodsList.splice(index, 1);
              this.$message.success('删除成功');
            }).catch(err => {
              console.log(err);
            });
          }
          else{
            this.form.crushGoodsList.splice(index, 1);
            this.$message.success('删除成功');
          }
        }).catch(err => {
          console.log(err);
        });
      },
      // 根据兰蜜价和最高佣金计算大区价和董事价
      calcOtherPrice(index, subIndex){
        let query = {
          lmPrice: this.form.crushGoodsList[index].goodsAttr[subIndex].price,
          highestCommission: this.form.crushGoodsList[index].goodsAttr[subIndex].maximumCommission
        };
        this.calcRDPrice(query, (data) => {
          this.form.crushGoodsList[index].goodsAttr[subIndex].regionPrice = data.regionPrice;
          this.form.crushGoodsList[index].goodsAttr[subIndex].directorPrice = data.directorPrice;
          this.form.crushGoodsList[index].goodsAttr[subIndex].diamondPrice = data.diamondPrice;
        });
      },
      uploadAttrImg(item, event) {
        const file = event.target.files[0];
        this.picFileUpload(file, (res) => {
          this.$set(item, 'skuImage', this.replaceImgUrl(res.filePath));
        });
      },
      save(){
        this.$refs.form.validate(valid => {
          if (!valid) {
            return false;
          }
          this.form.goodsAttr = [];
          let noSkuGoods = [];
          let skuNumFlag = false;
          let priceFlag = false;
          this.form.crushGoodsList.map(item => {
            if(item.type ===1 && item.goodsAttr.length){
              item.goodsAttr.map(subItem => {
                if(!(subItem.totalSkuNumber+(subItem.distributedSkuNumber||0)) && subItem.deleteFlag && subItem.upshelf){
                  skuNumFlag = true;
                }
                if(!(subItem.marketValue>0 && subItem.price>0) && subItem.deleteFlag && subItem.upshelf){
                  priceFlag = true;
                }
                this.form.goodsAttr.push({
                  ...subItem,
                  associationId: this.id
                })
              })
            } else if(item.type ===1 && !item.goodsAttr.length){
              noSkuGoods.push(item)
            }
          });
          if(skuNumFlag){
            this.$message.warning('存在0库存的规格商品，请先下架再保存');
          } else if(priceFlag){
            this.$message.warning('存在价格为0的商品，请先设置价格再保存');
          } else if(!noSkuGoods.length){
            this.btnLoading = true;
            console.log(this.form)
            this.form.crushGoodsList.forEach((item, index) =>{
            // 排除套餐无商品
             item.goodsAttr && item.goodsAttr.forEach((item_c, index_c) => {
                if (item_c.maximumCommission == 0) {
                  item_c.regionPrice = item_c.price
                  item_c.diamondPrice = item_c.price
                  item_c.directorPrice = item_c.price
                }
              })
            })
            this.form.goodsAttr.forEach((item, index) =>{
              if (item.maximumCommission == 0) {
                item.regionPrice = item.price
                item.diamondPrice = item.price
                item.directorPrice = item.price
              }
            })
            this.request({
              url: '/bsnl-product/crushgoods/create',
              method: 'post',
              data: this.form
            }).then(() => {
              this.$message.success('保存成功');
              this.btnLoading = false;
              this.$router.back();
            }).catch(err => {
              this.btnLoading = false;
              console.log(err);
            });
          } else {
            let msg = '商品【';
            noSkuGoods.map((item, index) => {
              msg+=item.goodsName;
              msg+=(index===noSkuGoods.length-1?'】没有SKU信息，请先移除对应的商品':'、');
            });
            this.$message({
              message: msg,
              type: 'warning'
            });
          }
        });
      }
    }
  }
</script>
<style lang="scss">
    @import "../../../../styles/mixin";
    .el-table__expanded-cell[class*=cell] {
        padding: 20px;
    }
    .el-table__body .el-select,
    .el-table__body .el-input{
        width: 100% !important;
    }
    .time-goods-list{
        @include scrollbar();
        max-height: 300px;
    }
</style>
